using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Threading;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Xml.Linq;
using Code5Systems.FormMaster.Business;
using DotNetNuke.Entities.Users;
using DotNetNuke.Services.Localization;

namespace Code5Systems.FormMaster
{

	public partial class FormMaster : DotNetNuke.Entities.Modules.PortalModuleBase, DotNetNuke.Entities.Modules.IActionable, DotNetNuke.Entities.Modules.IPortable
	{
		
#region Private Members
		
		private Code5Systems.FormMaster.Business.FormInfo _objFormInfo;
		private XDocument _xDoc;
		private XDocument _objResultsXmlDoc;
		private Code5Systems.FormMaster.Business.FormController _objFormCtl;
		private bool _bSendMail = true;
		private string _strFormAdminErrorMsg = "";
		private FormSettings _objFormSettings;
		private Code5Systems.FormMaster.Business.FormDataController _oFormDataCtl;
		private string _validationGroup;
		private bool _hasValidation = false;
		private bool _hasFileUploadControls = false;
		private int _formDataId; // VBConversions Note: Initial value of "Null.NullInteger" cannot be assigned here since it is non-static.  Assignment has been moved to the class constructors.
		private Code5Systems.FormMaster.Business.FormPostResult _postResult = Code5Systems.FormMaster.Business.FormPostResult.Success;
		private int _userId;
		private bool _isShowUnlicensed = false;
		private List<Control> _submitButtons = new List<Control>();
		private bool _isMultiPage = false;
		private List<string> _disabledValidators = new List<string>();
		private HtmlInputHidden _hdnWzrdStart;
		private HtmlGenericControl _head;

#endregion
		
#region Web Form Designer Generated Code
		
		//This call is required by the Web Form Designer.
		[System.Diagnostics.DebuggerStepThrough()]private void InitializeComponent()
		{
			
		}

		protected System.Web.UI.WebControls.Panel pnlForm;
		protected System.Web.UI.WebControls.Panel pnlThankYou;
		protected System.Web.UI.WebControls.Label lblThankYou;
		protected System.Web.UI.HtmlControls.HtmlTable tblThankYou;
		protected System.Web.UI.WebControls.Label lblIFrame;
		protected System.Web.UI.WebControls.HyperLink hlDownload;
		
		//NOTE: The following placeholder declaration is required by the Web Form Designer.
		//Do not delete or move it.
		private System.Object designerPlaceholderDeclaration;
		
		private void Page_Init(System.Object sender, System.EventArgs e)
		{
			//CODEGEN: This method call is required by the Web Form Designer
			//Do not modify it using the code editor.
			InitializeComponent();
			Response.Buffer = true;
			
			try
			{
				var adapters = Context.Request.Browser.Adapters;
				var radioButtonListType = typeof(C5RadioButtonList).AssemblyQualifiedName;
				var rbAdapterType = typeof(C5RadioButtonListAdapter).AssemblyQualifiedName;
				if (!adapters.Contains(radioButtonListType))
				{
					adapters.Add(radioButtonListType, rbAdapterType);
				}

				var checkBoxListType = typeof(C5CheckBoxList).AssemblyQualifiedName;
				var cbListAdapterType = typeof(C5CheckBoxListAdapter).AssemblyQualifiedName;
				if (!adapters.Contains(checkBoxListType))
				{
					adapters.Add(checkBoxListType, cbListAdapterType);
				}

				var checkBoxType = typeof(C5CheckBox).AssemblyQualifiedName;
				var cbAdapterType = typeof(C5CheckBoxAdapter).AssemblyQualifiedName;
				if (!adapters.Contains(checkBoxType))
				{
					adapters.Add(checkBoxType, cbAdapterType);
				}


				DotNetNuke.Framework.jQuery.RequestRegistration();
				
				//Get the Module Settings
				_objFormSettings = Utility.GetFormSettings(ModuleId);

				_objFormCtl = new Code5Systems.FormMaster.Business.FormController(ModuleId);
				
				//Get the FormInfo Object
				_objFormInfo = _objFormCtl.FormInfo;
				
				if (_objFormInfo == null)
				{
					UserController objUsers = new UserController();
					UserInfo objUser = UserController.GetCurrentUserInfo();
					if (objUser.IsSuperUser || DotNetNuke.Security.PortalSecurity.IsInRole("Administrators"))
					{
						Response.Redirect(DotNetNuke.Common.Globals.NavigateURL(TabId, "", "ctl=Dispatcher", "mid=" + ModuleId));
					}
					else
					{
						throw (new Exception(Localization.GetString("FormDataLoadError", this.LocalResourceFile)));
					}
				}

				Utility.DoLogging(this.PortalId, this.ModuleId, "Licence Check Complete", base.ModuleContext);

				#region Create Form

				_head = this.Page.FindControl("Head") as HtmlGenericControl;
				
				_hdnWzrdStart = this.pnlForm.FindControl("hdnWzrdStart") as HtmlInputHidden;
				if(_hdnWzrdStart == null)
				{
					_hdnWzrdStart = new HtmlInputHidden() { ID = "hdnWzrdStart", Value = "0" };
					_hdnWzrdStart.Attributes.Add("class", String.Format("C5S_wzrdstart_{0}", this._objFormInfo.FormID));
					this.phForm.Controls.Add(_hdnWzrdStart);
				}
				

				if (String.IsNullOrWhiteSpace(_objFormInfo.FormDefinition))
				{
					//If there is no FormDefinition, get the default definition from Resources
					_objFormCtl.UpdateFormDefinition(ModuleId, Localization.GetString("BaseForm", Utility.GetSharedResourceFile()), this.UserId);
				}
				else
				{
					this._xDoc = XDocument.Parse(_objFormInfo.CurrentPage.PageData);
				}

				if (!_objFormInfo.UseCaptcha || _objFormSettings.CaptchaType == CaptchaType.GoogleReCaptcha)
				{
					this.ctl_c5sllc_Captcha.Visible = false;
					lblCaptchaErrMsg.Text = string.Empty;
				}
				else if (_objFormSettings.CaptchaType == CaptchaType.DefaultCaptcha)
				{
					ctl_c5sllc_Captcha.CaptchaChars = System.Convert.ToString((_objFormInfo.CaptchaCharacters == string.Empty ? (Localization.GetString("CaptchaCharaters", Utility.GetSharedResourceFile())) : _objFormInfo.CaptchaCharacters).ToString());
				}
				
				if (_objFormCtl.Pages.Count == 1)
				{
					_hasFileUploadControls = (from s in this._xDoc.Root.Elements("Controls").Elements("Control") where s.Attributes("Type").First().Value == "FileUpload" orderby s.Attributes("TableRow").First().Value select s).Count() > 0;

					if (_objFormSettings.ResponsiveLayout)
					{
						this._objFormCtl.CreateFormRwd(ModuleId, this.pnlForm, false);
					}
					else
					{
						this._objFormCtl.CreateForm(ModuleId, this.pnlForm, false);
					}

					this.phForm.Visible = true;
					_validationGroup = _objFormCtl.FormInfo.ValidationGroup;
					_hasValidation = _objFormCtl.HasValidators;
					
					if (_objFormSettings.ResponsiveLayout)
					{
						RegisterEventHandlersRwd();
					}
					else
					{
						RegisterEventHandlers();
					}
				}
				else
				{
					HtmlGenericControl wzrdScriptTag;
#if DEBUG
					if (_head != null && _head.FindControl("C5SLLC_wizard") == null)
					{
						wzrdScriptTag = new HtmlGenericControl("script");
						wzrdScriptTag.ID = "C5SLLC_wizard";
						wzrdScriptTag.Attributes.Add("type", "text/javascript");
						wzrdScriptTag.Attributes.Add("src", String.Format("{0}DesktopModules/Code5Systems_FormMaster/assets/js/jquery-formToWizard.js", Utility.GetAppPath()));
						_head.Controls.Add(wzrdScriptTag);
					}
#else

					if (_head != null && _head.FindControl("C5SLLC_wizard") == null)
					{
						wzrdScriptTag = new HtmlGenericControl("script");
						wzrdScriptTag.ID = "C5SLLC_wizard";
						wzrdScriptTag.Attributes.Add("type", "text/javascript");
						wzrdScriptTag.Attributes.Add("src", String.Format("{0}DesktopModules/Code5Systems_FormMaster/assets/js/jquery-formToWizard.min.js", Utility.GetAppPath()));
						_head.Controls.Add(wzrdScriptTag);
					}
#endif
					_validationGroup = _objFormCtl.FormInfo.ValidationGroup;
					_isMultiPage = true;
					this.phForm.CssClass = String.Format("C5SLLC_wizard_{0}", this._objFormInfo.FormID);

					if (!String.IsNullOrWhiteSpace(_objFormSettings.TableWidth))
					{
						phForm.Width = Unit.Parse(_objFormSettings.TableWidth);
					}

					switch (_objFormSettings.TableAlignment)
					{
						case HorizontalAlign.Left:
							this.phForm.CssClass += " C5SLLC_left";
							break;
						case HorizontalAlign.Center:
							this.phForm.CssClass += " C5SLLC_center";
							break;
						case HorizontalAlign.Right:
							this.phForm.CssClass += " C5SLLC_right";
							break;
					}
				
					foreach (Code5Systems.FormMaster.Business.FormPageInfo oPage in _objFormCtl.Pages)
					{
						_objFormCtl.FormInfo.CurrentPage = oPage;
						if (!_hasFileUploadControls)
						{
							this._xDoc = XDocument.Parse(oPage.PageData);
							_hasFileUploadControls = (from s in this._xDoc.Root.Elements("Controls").Elements("Control") 
													  where s.Attributes("Type").First().Value == "FileUpload" 
													  orderby s.Attributes("TableRow").First().Value 
													  select s).Count() > 0;
						}
						
						HtmlGenericControl fieldSet = new HtmlGenericControl("fieldset");
						fieldSet.ID = String.Format("C5SLLC_Step{0}", oPage.PageNum);

						if(!String.IsNullOrWhiteSpace(_objFormSettings.FormTableWidth))
						{
							if(_objFormSettings.FormTableWidth.EndsWith("%"))
							{
								fieldSet.Attributes.Add("style", String.Format("width:{0};", _objFormSettings.FormTableWidth));
							}
							else
							{
								fieldSet.Attributes.Add("style", String.Format("width:{0}px;", _objFormSettings.FormTableWidth));
							}
							
						}

						switch (_objFormSettings.TableAlignment)
						{
							case HorizontalAlign.Left:
								fieldSet.Attributes.Add("class", "C5SLLC_left");
								break;
							case HorizontalAlign.Center:
								fieldSet.Attributes.Add("class", "C5SLLC_center");
								break;
							case HorizontalAlign.Right:
								fieldSet.Attributes.Add("class", "C5SLLC_right");
								break;
						}

						HtmlGenericControl legend = new HtmlGenericControl("legend");
						legend.InnerText = oPage.ShortName;
						switch (_objFormSettings.WizardLegendAlign)
						{
							case HorizontalAlign.Left:
								legend.Attributes.Add("class", String.Format("textleft {0}", _objFormSettings.WizardLegendClass));
								break;
							case HorizontalAlign.Center:
								legend.Attributes.Add("class", String.Format("textcenter {0}", _objFormSettings.WizardLegendClass));
								break;
							case HorizontalAlign.Right:
								legend.Attributes.Add("class", String.Format("textright {0}", _objFormSettings.WizardLegendClass));
								break;
							default:
								legend.Attributes.Add("class", _objFormSettings.WizardStepClass);
								break;
						}
						
						fieldSet.Controls.Add(legend);

						if (_objFormCtl.FormInfo.CurrentPage.UseTitle)
						{
							string titleClass = String.Format("frmwizardheader {0}",_objFormSettings.WizardStepTitleClass);
							string titleStyle = String.Empty;
							HtmlGenericControl pageTitle = new HtmlGenericControl("div");
							pageTitle.InnerHtml = oPage.Title;

							switch (_objFormSettings.WizardTitleAlign)
							{
								case HorizontalAlign.Left:
									titleClass += " textleft";
									break;
								case HorizontalAlign.Center:
									titleClass += " textcenter";
									break;
								case HorizontalAlign.Right:
									titleClass += " textright";
									break;
							}
							
							pageTitle.Attributes.Add("class", titleClass);
							//pageTitle.Attributes.Add("style", titleStyle);
							fieldSet.Controls.Add(pageTitle);
						}
						
						

						this.phForm.Controls.Add(fieldSet);

						if (_objFormSettings.ResponsiveLayout)
						{
							this._objFormCtl.CreateFormRwd(ModuleId, fieldSet, false);
						}
						else
						{
							this._objFormCtl.CreateForm(ModuleId, fieldSet, false);
						}
					}

					if (_objFormSettings.ResponsiveLayout)
					{
						RegisterEventHandlersRwd();
					}
					else
					{
						RegisterEventHandlers();
					}

					this._objFormCtl.SetWizardCallScripts(this.pnlDynScripts);
				}

				if (_objFormSettings.ResponsiveLayout)
				{
					if (!String.IsNullOrWhiteSpace(_objFormSettings.TableWidth))
					{
						if (_objFormSettings.TableWidth.Contains("%"))
						{
							double width;
							if (double.TryParse(_objFormSettings.TableWidth, out width))
							{
								this.pnlForm.Width = Unit.Percentage(width);
							}
						}
						else
						{
							int width;
							if (int.TryParse(_objFormSettings.TableWidth, out width))
							{
								this.pnlForm.Width = Unit.Pixel(width);
							}
						}

						this.pnlForm.CssClass = "C5SLLC_width";
					}

					if (_objFormSettings.TableAlignment != HorizontalAlign.NotSet)
					{
						switch (_objFormSettings.TableAlignment)
						{
							case HorizontalAlign.Center:
								this.pnlForm.CssClass = "C5SLLC_width C5SLLC_center";
								break;
							case HorizontalAlign.Left:
								this.pnlForm.CssClass = "C5SLLC_width C5SLLC_left";
								break;
							case HorizontalAlign.Right:
								this.pnlForm.CssClass = "C5SLLC_width C5SLLC_right";
								break;
						}
					}
				}

				#endregion Create Form
			}
			catch (Exception ex)
			{
				DotNetNuke.UI.Skins.Skin.AddModuleMessage(this, ex.Message, DotNetNuke.UI.Skins.Controls.ModuleMessage.ModuleMessageType.RedError);
				DotNetNuke.Services.Exceptions.Exceptions.LogException(ex);
				Utility.DoLogging(this.PortalId, this.ModuleId, ex.Message, base.ModuleContext);
			}
			
		}
		
#endregion
		
#region Properties
		protected string StepCssClass
		{
			get
			{
				return _objFormSettings.WizardStepClass;
			}
		}
#endregion
		
#region Event Handlers
		
		private void Page_Load(System.Object sender, System.EventArgs e)
		{
			
			try
			{
				if (this._objFormCtl.HasCalculation)
				{
					_objFormCtl.GenerateCalxScrpts(this.pnlForm, this.pnlDynScripts);

					if (_head != null)
					{
						HtmlGenericControl calxScriptTag;
#if DEBUG
						if (_head.FindControl("C5SLLC_calx") == null)
						{
							calxScriptTag = new HtmlGenericControl("script");
							calxScriptTag.ID = "C5SLLC_calx";
							calxScriptTag.Attributes.Add("type", "text/javascript");
							calxScriptTag.Attributes.Add("src", String.Format("{0}DesktopModules/Code5Systems_FormMaster/assets/js/jquery-calx-1.1.8.js", Utility.GetAppPath()));
							_head.Controls.Add(calxScriptTag);
						}
#else
					if (_head.FindControl("C5SLLC_calx") == null)
					{
						calxScriptTag = new HtmlGenericControl("script");
						calxScriptTag.ID = "C5SLLC_calx";
						calxScriptTag.Attributes.Add("type", "text/javascript");

						calxScriptTag.Attributes.Add("src", String.Format("{0}DesktopModules/Code5Systems_FormMaster/assets/js/jquery-calx-1.1.8.min.js", Utility.GetAppPath()));
						_head.Controls.Add(calxScriptTag);
					}
#endif
					}
				}

				//_objFormCtl.GeneratePageScripts(this.pnlForm, false, DotNetNuke.Framework.AJAX.IsEnabled());
				this.PageLoad(sender, e);
				
			}
			catch (ThreadAbortException)
			{
				//Do dothing on Redirect
			}
			catch (Exception exc)
			{
				DotNetNuke.UI.Skins.Skin.AddModuleMessage(this, exc.Message, DotNetNuke.UI.Skins.Controls.ModuleMessage.ModuleMessageType.RedError);
				DotNetNuke.Services.Exceptions.Exceptions.LogException(exc);
			}
		}
		
		private void Submit_Click(object sender, System.Web.UI.WebControls.CommandEventArgs e)
		{

			List<string> _disabledValidators = Utility.GetSessionItem<string>(Code5Systems.FormMaster.Business.Constants.DISABLED_RULE_VALIDATORS).FromCSV();

			if (_disabledValidators.Count > 0)
			{
				foreach (BaseValidator val in Utility.GetChildsRecursive(this.pnlForm).OfType<BaseValidator>())
				{
					if (_disabledValidators.Contains(val.ClientID))
					{
						val.Enabled = false;
					}
				}
			}
			
			Page.Validate(this._objFormInfo.ValidationGroup);
			if (Page.IsValid && CheckCaptcha())
			{
				try
				{
					this.SubmitClick(sender, e);
				}
				catch (IOException exIO)
				{
					DotNetNuke.UI.Skins.Skin.AddModuleMessage(this, exIO.Message, DotNetNuke.UI.Skins.Controls.ModuleMessage.ModuleMessageType.YellowWarning);
				}
				catch (SqlException exSql)
				{
					DotNetNuke.UI.Skins.Skin.AddModuleMessage(this, exSql.Message, DotNetNuke.UI.Skins.Controls.ModuleMessage.ModuleMessageType.YellowWarning);
				}
				catch (ThreadAbortException)
				{
					//Do Nothing this is a redirect
				}
				catch (Exception exc)
				{
					DotNetNuke.UI.Skins.Skin.AddModuleMessage(this, exc.Message, DotNetNuke.UI.Skins.Controls.ModuleMessage.ModuleMessageType.RedError);
					DotNetNuke.Services.Exceptions.Exceptions.LogException(exc);
				}
			}
			else 
			{
				foreach (BaseValidator val in Utility.GetChildsRecursive(this.pnlForm).OfType<BaseValidator>())
				{
					FormControlInfo frmCtrlInfo;
					Fortunate.Web.CheckBoxListRequiredFieldValidator chkBxValidator = null;
					if (!val.IsValid)
					{
						if (chkBxValidator == null && val.GetType().Name == "CheckBoxListRequiredFieldValidator")
						{
							chkBxValidator = val as Fortunate.Web.CheckBoxListRequiredFieldValidator;
						}

						foreach (var page in _objFormCtl.Pages)
						{
							this._objFormInfo.CurrentPage = page;
							if (chkBxValidator != null)
							{
								frmCtrlInfo = _objFormCtl.GetFormControlInfo(this._objFormInfo, chkBxValidator.ControlToValidate);
							}
							else
							{
								frmCtrlInfo = _objFormCtl.GetFormControlInfo(this._objFormInfo, ((BaseValidator)val).ControlToValidate);
							}
							
							if (frmCtrlInfo != null)
							{
								_hdnWzrdStart.Value = (frmCtrlInfo.Page -1).ToString();
								return;
							}
						}
						
					}
				}
			}
		}
		
#endregion
		
#region Optional Interfaces
		
		public DotNetNuke.Entities.Modules.Actions.ModuleActionCollection ModuleActions
		{
			get
			{
				DotNetNuke.Entities.Modules.Actions.ModuleActionCollection Actions = new DotNetNuke.Entities.Modules.Actions.ModuleActionCollection();
				Actions.Add(GetNextActionID(), Localization.GetString(DotNetNuke.Entities.Modules.Actions.ModuleActionType.AddContent, LocalResourceFile), DotNetNuke.Entities.Modules.Actions.ModuleActionType.AddContent, "", "", EditUrl("Dispatcher"), false, DotNetNuke.Security.SecurityAccessLevel.Edit, true, false);
				return Actions;
			}
		}
		
		public string ExportModule(int ModuleID)
		{
			// included as a stub only so that the core knows this module Implements Entities.Modules.IPortable
			return null;
		}
		
		public void ImportModule(int ModuleID, string Content, string Version, int UserID)
		{
			// included as a stub only so that the core knows this module Implements Entities.Modules.IPortable
		}
		
#endregion
		
	}
	
}


